package Pipe;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 过滤器 实现移位操作
 * @author fengke
 */
public class Shift extends Filter{
    /**
     * wordList单词的列表
     * lneList重组后的行的列表
     */
    private ArrayList<String> wordList = new ArrayList<String>();
    private ArrayList<String> lineList = new ArrayList<String>();

    Shift(Pipe input, Pipe output){
        super(input, output);
    }

    @Override
    protected void transform() throws IOException {
        String tempLine = "";
        // 以行为单位读数据
        while((tempLine = input.readerLine()) != null){
            //将数据拆分为不同单词
            this.lineSplitWord(tempLine);
            //将单词重组为句子
            this.recombination();
            //输出重组结果
            for(int i = 0; i < lineList.size(); i++){
                output.writerLine(lineList.get(i));
            }
            //清空wordlist、lineList和tempLine
            wordList.clear();
            lineList.clear();
            tempLine = "";
        }
        input.closeReader();
        output.closeWriter();
    }

    private void lineSplitWord(String line){
        String word = "";
        int i = 0;
        while(i < line.length()){
            if(line.charAt(i) != ' '){
                word += line.charAt(i);
            }
            else{
                wordList.add(word);
                word = "";
            }
            i++;
        }
        if (word.length() > 0) {
            wordList.add(word);
        }
    }

    private void recombination(){
        for(int j = 0; j < wordList.size(); j++){
            String tempLine = "";
            for (int k = wordList.size() - 1 - j; k < wordList.size(); k++){
                tempLine += wordList.get(k) + " ";
            }
            for (int m = 0; m < wordList.size() - 1 - j; m++){
                if(m != wordList.size() - j - 2){
                    tempLine += wordList.get(m) + " ";
                }
                else{
                    tempLine += wordList.get(m);
                }
            }
            lineList.add(tempLine);
        }
    }
}

